// ProjectName: go-learn-demo
// PackageName: _0_redis
// Description:
// Author: hy.bai
// Date: 2025-08-25 星期一 9:52

package redisybxb

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"log/slog"
)

func InitClient() (*redis.Client, *context.Context, error) {
	// context.Background()作用是用于控制Redis请求的上下文的
	ctx := context.Background()
	// 拼装的URL地址是："redis://:HF55hdut6zKVBf7@192.168.18.20:16379/0"
	url := fmt.Sprintf("redis://:%s@%s:%d/%d", REDIS_PASSWORD, REDIS_ADDR, REDIS_PORT, REDIS_DB)
	redisOptions, err := redis.ParseURL(url)
	if err != nil {
		panic(fmt.Sprintf("解析Redis的URL链接信息失败,原因是:%s", err.Error()))
	}
	redisOptions.PoolSize = REDIS_PoolSize
	redisOptions.MinIdleConns = REDIS_MinIdleConns
	redisOptions.WriteTimeout = REDIS_WriteTimeout
	redisOptions.ReadTimeout = REDIS_ReadTimeout
	client := redis.NewClient(redisOptions) // 注意:此时并没有发起连接。
	status := client.Ping(ctx)              // ping操作时，才会发起连接
	slog.Info(fmt.Sprintf("Status: %v", status.Val()))
	return client, &ctx, nil
}

func TestInitClient1() {
	rOpt := &redis.Options{
		Addr:         fmt.Sprintf("%s:%d", REDIS_ADDR, REDIS_PORT),
		Password:     REDIS_PASSWORD,
		DB:           REDIS_DB,
		PoolSize:     REDIS_PoolSize,     // 设置连接池：最大连接数
		MinIdleConns: REDIS_MinIdleConns, // 设置连接池：最小空闲连接数
		WriteTimeout: REDIS_WriteTimeout, // 设置连接池：写超时
		ReadTimeout:  REDIS_ReadTimeout,  // 设置连接池：读超时
	}
	client := redis.NewClient(rOpt)
	ctx := context.Background()
	status := client.Ping(ctx)
	slog.Info(fmt.Sprintf("status: %v", status))
}

func TestInitClient2() {
	client, ctx, err := InitClient()
	slog.Info(fmt.Sprintf("client: %v, ctx: %v, err: %v", client, ctx, err))
}
